﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityMultiPlayerGameServer.Clients;

namespace UnityMultiPlayerGameServer.Manager
{
    internal class ClientManager
    {
        private static readonly object locker = new object();
        private static ClientManager instance;
        public static ClientManager Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                        {
                            instance = new ClientManager();
                        }
                    }

                }
                return instance;
            }
        }

        /// <summary>
        /// 未登录客户端列表
        /// </summary>
        private List<Client> clientList = new List<Client>();
        /// <summary>
        /// 已登录客户端字典
        /// string = 用户ID userData.AccountID
        /// </summary>
        private Dictionary<string, Client> loginClientDict = new Dictionary<string, Client>();

        public void AddClientList(Client client)
        {
            clientList.Add(client);
        }
        public void RemoveClientList(Client client)
        {
            clientList.Remove(client);
        }

        /// <summary>
        /// 将客户端放入已登录字典中
        /// </summary>
        /// <param name="client"></param>
        public void AddClientDict(Client client)
        {
            if(loginClientDict.ContainsKey(client.userInfo.AccountID))
            {
                //若已登录客户端字典中存在当前用户ID的在其他地方登录的客户端，则先移除之前的客户端
                //loginClientDict[client.userData.AccountID].Close();
                loginClientDict.Remove(client.userInfo.AccountID);
                Console.WriteLine(client.userInfo.AccountID + "移除其他地点已登录的客户端");
            }
            //将当前客户端从未登录客户端列表中移除
            RemoveClientList(client);
            loginClientDict.Add(client.userInfo.AccountID, client);
        }

        /// <summary>
        /// 将客户端从字典移除并关闭客户端
        /// </summary>
        /// <param name="client"></param>
        public void RemoveClientDict(Client client)
        {
            client.Close();
            loginClientDict.Remove(client.userInfo.AccountID);
        }

        public Client FindClientByAccountID(string ID)
        {
            if(loginClientDict.ContainsKey(ID))
            {
                return loginClientDict[ID];
            }

            return null;
        }
    }
}
